package org.ricks.condition2.test;

import org.ricks.condition2.ComparisonOperator;
import org.ricks.condition2.Condition;
import org.ricks.condition2.Conditions;
import org.ricks.condition2.event.MonsterKillEvent;
import org.ricks.condition2.event.PlayerLevelUpEvent;
import java.util.Arrays;
import java.util.List;
import java.util.function.Predicate;

public class ConditionParser {

    // 根据配置表动态创建条件
    public static Condition parseCondition(String playerId, ConditionConfig config) {
        return switch (config.getType()) {
            case PLAYER_LEVEL -> createPlayerLevelCondition(playerId, config);
            case KILL_MONSTER -> createKillMonsterCondition(playerId, config);
            case COMPOSITE_AND -> createCompositeCondition(playerId, config, list -> list.stream().allMatch(Condition::isDone));
            case COMPOSITE_OR -> createCompositeCondition(playerId, config, list -> list.stream().anyMatch(Condition::isDone));
            default -> throw new IllegalArgumentException("Unsupported condition type: " + config.getType());
        };
    }

    // 玩家等级条件
    private static Condition createPlayerLevelCondition(String playerId, ConditionConfig config) {
        return Conditions.genericProgress(
                playerId,
                0, // 初始等级为0（实际应从玩家数据读取）
                config.getTargetValue(),
                e -> true, // 所有升级事件都处理
                (current, event) -> Math.max(current, event.newLevel()), // 直接取最新等级
                Integer::compare,
                ComparisonOperator.parse(config.getOperator()),
                PlayerLevelUpEvent.class
        );
    }

    // 击杀怪物条件
    private static Condition createKillMonsterCondition(String playerId, ConditionConfig config) {
        int monsterId = Integer.parseInt(config.getParam1());
        return Conditions.genericProgress(
                playerId,
                0,
                config.getTargetValue(),
                 e -> e.monsterId() == monsterId,
                (count, event) -> count + event.num(),
                Integer::compare,
                ComparisonOperator.parse(config.getOperator()),
                MonsterKillEvent.class
        );
    }

    // 复合条件
    private static Condition createCompositeCondition(String playerId, ConditionConfig config, Predicate<List<Condition>> predicate) {
        List<Condition> children = Arrays.stream(config.getParam1().split(","))
                .map(id -> parseCondition(playerId, loadConditionConfig(Integer.parseInt(id))))
                .toList();
        return Conditions.composite(playerId, predicate, children.toArray(new Condition[0]));
    }

    private static ConditionConfig loadConditionConfig(int conditionId) {
        ConditionConfig config = new ConditionConfig();
        return config;
    }
}
